#ifndef __BMPREADER__
#define __BMPREADER__

#include <stdio.h>
#include <stdlib.h>
#include "IMG.h"


void readBMP(IMG *img, FILE *fpbmp){
	img->empty = 0;
	unsigned short bfType = 0;
	fseek(fpbmp, 0L, SEEK_SET);
	if (fread(&bfType, sizeof(char), 2, fpbmp) != 2){
		img->empty = 1;
		return;
	}
	if (19778 != bfType){
		img->empty = 1;
		return;
	}
	fseek(fpbmp, 18L, SEEK_SET);
	if (fread(&img->width, sizeof(char), 4, fpbmp) != 4){
		img->empty = 1;
		return;
	}
	if (fread(&img->height, sizeof(char), 4, fpbmp) != 4){
		img->empty = 1;
		return;
	}
	int lReverse = 0;
	if (img->height < 0){
		lReverse = 1;
		img->height = - img->height;
	}



	unsigned short t;
	if (fread(&t, sizeof(char), 2, fpbmp) != 2){
		img->empty = 1;
		return;
	}
	if (fread(&t, sizeof(char), 2, fpbmp) != 2){
		img->empty = 1;
		return;
	}

	if (t == 24)
		img->channels = 3;
	else if (t == 8)
		img->channels = 1;
	else if (t ==32)
		img->channels = 4;
	else {
		img->empty = 1;
		return;
	}
	fseek(fpbmp, 10L, SEEK_SET);
	long offset;
	if (fread(&offset, sizeof(char), 4, fpbmp) != 4){
		img->empty = 1;
		return;
	}
	fseek(fpbmp, offset, SEEK_SET);
	img->data = (unsigned char**)malloc(img->height*sizeof(unsigned char*));
	if (img->data == NULL){
		img->empty = 1;
		return;
	}
	long rowlenth = img->width*img->channels;
	if (rowlenth % 4 != 0){
		rowlenth += 4 - (rowlenth % 4);
	}
	int i = 0, j = 0;
	if (lReverse == 1){
		for (i = 0; i < img->height; i++){
			img->data[i] = (unsigned char*)malloc(rowlenth*sizeof(unsigned char));
			if (img->data == NULL){
				for (j = 0; j < i; j++){
					free(img->data[j]);
				}
				free(img->data);
				img->empty = 1;
				return;
			}
			if (fread(img->data[i], sizeof(char), rowlenth, fpbmp) != rowlenth){
				for (j = 0; j < i + 1; j++){
					free(img->data[j]);
				}
				free(img->data);
				img->empty = 1;
				return;
			}
		}
	}
	else{
		for (i = img->height - 1; i >= 0; i--){
			img->data[i] = (unsigned char*)malloc(rowlenth*sizeof(unsigned char));
			if (img->data == NULL){
				for (j = img->height - 1; j > i; j++){
					free(img->data[j]);
				}
				free(img->data);
				img->empty = 1;
				return;
			}
			if (fread(img->data[i], sizeof(char), rowlenth, fpbmp) != rowlenth){
				for (j = img->height - 1; j < i - 1; j++){
					free(img->data[j]);
				}
				free(img->data);
				img->empty = 1;
				return;
			}
		}
	}
	
	return;
}
void freeIMG(IMG *bmp){
	if (!bmp->empty){
		int i = 0;
		for (i = 0; i < bmp->height; i++){
			free(bmp->data[i]);
		}
		free(bmp->data);
		bmp->empty = 1;
	}
}

#endif